﻿using Bll;
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Web.Models;

namespace Web.Controllers
{
    public class BaseController : Controller
    {
        public BaseController()
        {
            this.User = GetUser();
        }
        public new SysUser User { get; set; }
        private readonly string Babyface = "Babyface";
        private readonly string UserInfo = "UserInfo";

        public void LoginUser(SysUser user)
        {
            //存值
            HttpCookie cookieBabyface = new HttpCookie(Babyface);
            string jsonUser = JsonConvert.SerializeObject(user);
            cookieBabyface.Values.Add(UserInfo, jsonUser);
            cookieBabyface.Expires = DateTime.Now + new TimeSpan(0, 12, 0, 0);//cookie过期时间12小时
            Response.AppendCookie(cookieBabyface);
        }

        public SysUser GetUser()
        {
            HttpCookie cookieBabyface = Request.Cookies[Babyface];
            if (cookieBabyface != null)
            {
                string jsonUser = cookieBabyface[UserInfo];
                var user = JsonConvert.DeserializeObject<SysUser>(jsonUser);
                return user;
            }
            return null;
        }

        public void ClearCookie()
        {
            if (Request.Cookies[Babyface] != null)
            {
                HttpCookie cookieBabyface = Request.Cookies[Babyface];
                cookieBabyface.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(cookieBabyface);
            }
        }
    }
}
